from django.contrib import admin
from django.conf.urls import url
from django.http import HttpResponse
from chart.models import Chart
from chart.forms import ChartForm
from common.configs import configmanager
from custom.widgets import JsonifyConfigWidget


class ChartAdmin(admin.ModelAdmin):

    model = Chart

    def get_form(self, request, obj, **kwargs):
        return ChartForm

    def get_urls(self):
        urls = super(ChartAdmin, self).get_urls()
        my_urls = [url(r'^(?P<chart_pk>[-\w]+)/properties/formset/$', 
                       self.admin_site.admin_view(self.get_chart_properties_formset))]
        return my_urls + urls

    def get_chart_properties_formset(self, request, chart_pk=None):
        chart = Chart.objects.get(pk=chart_pk)
        field = JsonifyConfigWidget(configmanager.get_config('chart', chart.name)())
        return HttpResponse(field.render('chart', None))


admin.site.register(Chart, ChartAdmin)
